package com.pdsu.alumni.controller;


import com.pdsu.alumni.common.annotation.NoAuthentication;
import com.pdsu.alumni.common.result.Result;
import com.pdsu.alumni.pojo.SensitiveWords;
import com.pdsu.alumni.service.IESService;
import com.pdsu.alumni.service.ISensitivewordsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Acerola
 * @since 2022-03-16
 */
@Api(tags = "敏感词控制层")
@RestController
@RequestMapping("/sensitivewords")
public class SensitivewordsController {

    @Autowired
    private IESService esService;
    @Autowired
    private ISensitivewordsService sensitivewordsService;

    @ApiOperation("ES同步mysql敏感词数据")
    @NoAuthentication
    @PostMapping("/synchroniz")
    public Result mysqlToES() {
        List<SensitiveWords> list = sensitivewordsService.list();
        esService.saveAll(list);
        return new Result().success();
    }

    @ApiOperation("分词")
    @NoAuthentication
    @GetMapping("/getAnalyzes")
    public Result getAnalyzes(String keywords) {
        return new Result().success().put(esService.getAnalyzes(keywords));
    }

    @ApiOperation("检测敏感词")
    @NoAuthentication
    @GetMapping("/examine")
    public Result examine(String keywords) {
        //分词
        List<String> analyzes = esService.getAnalyzes(keywords);
        //按分词查询es
        List<SensitiveWords> strings = analyzes.stream()
                .flatMap(analyze -> esService.query(analyze).stream()
                ).collect(Collectors.toList());
        if (!strings.isEmpty())
            return new Result(201, "检测到敏感词汇", strings);
        else
            return new Result().success("无敏感词汇");
    }

    @ApiOperation("查询敏感词")
    @NoAuthentication
    @GetMapping("/query")
    public Result query() {
        return new Result().success().put(sensitivewordsService.list());
    }

    @ApiOperation("增加敏感词")
    @NoAuthentication
    @PostMapping("/insert")
    public Result insert(@RequestBody SensitiveWords sensitiveWords) {
        esService.save(sensitiveWords);
        return new Result().success().put(sensitivewordsService.save(sensitiveWords));
    }

    @ApiOperation("修改敏感词汇")
    @NoAuthentication
    @PostMapping("/update")
    public Result update(@RequestBody SensitiveWords sensitiveWords) {
        return new Result().success().put(sensitivewordsService.updateById(sensitiveWords));
    }

    @ApiOperation("删除敏感词汇")
    @NoAuthentication
    @PostMapping("/delete")
    public Result delete(@RequestBody SensitiveWords sensitiveWords) {
        esService.delete(sensitiveWords);
        return new Result().success().put(sensitivewordsService.removeById(sensitiveWords));
    }

}
